package com.code.pattern.prototype;

import lombok.Data;

import java.io.*;
import java.util.List;

/**
 * 原型模式
 * RealizeType - 具体的原型类
 * @author lyf
 * @date 2021-03-18 下午2:06
 */
@Data
public class RealizeType implements Cloneable,Serializable {

    private String name;

    private Integer age;

    private List<String> hobbies;

    RealizeType(String name, Integer age) {
        this.name = name;
        this.age = age;
        System.out.println("具体原型创建成功！");
    }

    /**
     * 这里也可以对异常进行catch处理，视情况而定
     * @return
     * @throws CloneNotSupportedException
     */
    public RealizeType clone() throws CloneNotSupportedException {
        System.out.println("具体原型复制成功！");
        return (RealizeType) super.clone();
    }

    //深克隆--将对象序列化到内存中在反序列化拿出来，得到一个新的对象
    public RealizeType deepClone() {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            oos.flush();
            oos.close();

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            RealizeType clone = (RealizeType)ois.readObject();
            ois.close();
            return clone;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
